/**
 * Definition for a binary tree node.
 * function TreeNode(val, left, right) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.left = (left===undefined ? null : left)
 *     this.right = (right===undefined ? null : right)
 * }
 */
/**
 * @param {TreeNode} root
 * @return {void} Do not return anything, modify root in-place instead.
 */
var flatten = function (root) {
  //记录上一个访问的节点
  let prev = null

  function dfs(node) {
    if (!node) return //如果节点为空，直接返回

    /*按照逆先序遍历（右、左、根）的顺序处理二叉树*/
    dfs(node.right)
    dfs(node.left)

    node.right = prev //当前节点的右指针指向上一节点
    node.left = null //当前节点的右指针置空 
    prev = node//更新上一节点为node
  }

  dfs(root)
};
